﻿/*#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code is not supported by Google
#
*/
/**
 * Parts of this code is taken from:
 * http://code.google.com/apis/gdata/docs/auth/clientlogin.html
 * http://code.google.com/apis/base/starting-out.html
 * http://code.google.com/apis/base/samples/java/java-sample.html
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;

namespace ShoppingAPI
{

    public class ClientLogin
    {
        /**
         * URL used for authenticating and obtaining an authentication token. 
         * More details about how it works:
         * <code>http://code.google.com/apis/accounts/AuthForInstalledApps.html<code>
         */
        private static string AUTHENTICATION_URL = "https://www.google.com/accounts/ClientLogin";

        private string EMAIL;
        private string PASSWORD;
        private string SERVICE;


        static void Main(string[] args)
        {
            ClientLogin sc = new ClientLogin(args[0], args[1], args[2]);
            Console.WriteLine(sc.authenticate());
        }

        public ClientLogin(string email, string password, string service)
        {
            this.EMAIL = email;
            this.PASSWORD = password;
            this.SERVICE = service;
        }

        public string authenticate()
        {
            String token = null;
            string postOutput = null;
            postOutput = makeLoginRequest(AUTHENTICATION_URL);

            // Parse the result of the login request. If everything went fine, the 
            // response will look like
            //      HTTP/1.0 200 OK
            //      Server: GFE/1.3
            //      Content-Type: text/plain 
            //      SID=DQAAAGgA...7Zg8CTN
            //      LSID=DQAAAGsA...lk8BBbG
            //      Auth=DQAAAGgA...dk3fA5N
            using (StringReader reader = new StringReader(postOutput))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] kp = line.Split('=');
                    if (kp[0] == "Auth")
                        token = kp[1];
                }
            }

            return token;
        }
        /**
         * Makes a HTTP POST request to the provided {@code url} given the provided
         * {@code parameters}. It returns the output from the POST handler as a
         * String object.
         * 
         * @param url the URL to post the request
         * @return the output from the Google Accounts server, as string
         * @throws IOException if an I/O exception occurs while
         *           creating/writing/reading the request
         */
        private string makeLoginRequest(string url)
        {
            // Create a login request. A login request is a POST request that looks like
            // POST /accounts/ClientLogin HTTP/1.0
            // Content-type: application/x-www-form-urlencoded
            // Email=johndoe@gmail.com&Passwd=north23AZ&service=structuredcontent&source=Insert Example
            WebRequest request =  WebRequest.Create(AUTHENTICATION_URL);
            request.Method = "POST";
            string postData = "Email=" + EMAIL + "&Passwd=" + PASSWORD + "&service=" + SERVICE + "&source=InsertExample";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse response = request.GetResponse();
             
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();

            if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
            {
                return responseFromServer;
            }

            reader.Close();
            dataStream.Close();
            response.Close();

            return "";

        }
    }

}
